import {
    NextRequest,
    NextResponse
} from 'next/server';
import {
    verifyToken
} from './lib/jwt';

const protectedPath = ['/dashboard', '/profile']
// pre  next
export async function middleware(req: NextRequest) {
    const pathname = req.nextUrl.pathname;
    // 非保护的
    if (!protectedPath.some(path => pathname.startsWith(path))) {
        return NextResponse.next();
    }
    // login?
    const accessToken = req.cookies.get('access_token')?.value;
    const refreshToken = req.cookies.get('refresh_token')?.value;
    if (!accessToken && !refreshToken) {
        return NextResponse.redirect(new URL('/login', req.url));
    }
    if (accessToken) {
        const accessPayload = await verifyToken(accessToken);
        if (accessPayload) {
            const requestHeaders = new Headers(req.headers);
            requestHeaders.set('x-user-id', accessPayload.userId as string);
            return NextResponse.next({
                request: {
                    headers: requestHeaders
                }
            });
        }
    }
    // accessToken失效了 无感刷新
    if (refreshToken) {
        const refreshPayload = await verifyToken(refreshToken);
        if (refreshPayload) {
            const refreshUrl = new URL('/api/auth/refresh', req.url);
            refreshUrl.searchParams.set('redirect', req.url);
            return NextResponse.redirect(refreshUrl);
        }
    }
    return NextResponse.redirect(new URL('/login', req.url));
}